const app = getApp();

Page({
  data: {
    content: '',
    images: [], // { tempPath, base64 }
    maxImages: 9,
    submitting: false
  },

  onContentInput(e) {
    this.setData({ content: e.detail.value });
  },

  onChooseImage() {
    const remaining = this.data.maxImages - this.data.images.length;
    if (remaining <= 0) return;

    // wx.chooseImage({
    //   count: remaining,
    //   sizeType: ['compressed'],
    //   sourceType: ['album', 'camera'],
    //   success: (res) => {
    //     const tempFiles = res.tempFilePaths || [];
    //     this.readImagesAsBase64(tempFiles);
    //   }
    // });
    wx.chooseMedia({
        count: remaining,
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        success: res => {
          const tasks = res.tempFiles.map(file => this.uploadImage(file))
          Promise.all(tasks).then(() => {
            wx.hideLoading()
          })
        }
    })
  },

  // 上传图片
  uploadImage(file) {
    wx.showLoading({ title: "上传中..." })
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: app.globalData.baseUrl + 'api/upload',
        filePath: file.tempFilePath,
        name: 'file',
        header: {
          'Authorization': `Bearer ${app.globalData.token}`
        },
        success: res => {
          const data = JSON.parse(res.data)
          if (data.code === 0) {
            this.setData({
              images: [...this.data.images, data.url]
            })
            resolve()
          } else {
            wx.showToast({
                title: "上传失败",
              icon: 'none'
            })
            reject()
          }
        },
        fail: () => {
          wx.showToast({
            title: "上传失败",
            icon: 'none'
          })
          reject()
        }
      })
    })
  },

  readImagesAsBase64(tempPaths) {
    const fs = wx.getFileSystemManager();
    const newItems = [];

    tempPaths.forEach((path) => {
      try {
        const base64 = fs.readFileSync(path, 'base64');
        newItems.push({ tempPath: path, base64: `data:image/jpg;base64,${base64}` });
      } catch (e) {
        console.warn('读取图片失败', e);
      }
    });

    this.setData({ images: [...this.data.images, ...newItems] });
  },

  onRemoveImage(e) {
    const index = e.currentTarget.dataset.index;
    const images = [...this.data.images];
    images.splice(index, 1);
    this.setData({ images });
  },

  onPreviewImage(e) {
    const index = e.currentTarget.dataset.index;
    wx.previewImage({
      current: this.data.images[index]?.tempPath,
      urls: this.data.images.map(it => it.tempPath)
    });
  },

  validateForm() {
    if (!this.data.content || this.data.content.trim() === '') {
      wx.showToast({ title: '请输入内容', icon: 'none' });
      return false;
    }
    return true;
  },

  async onSubmit() {
    if (this.data.submitting) return;
    if (!this.validateForm()) return;

    this.setData({ submitting: true });

    const token = wx.getStorageSync('token');
    const url = app.globalData.baseUrl + 'api/trend-post';
    const payload = {
      content: this.data.content.trim(),
      images: this.data.images
    };

    wx.request({
      url,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      data: payload,
      success: (res) => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          wx.showToast({ title: '发布成功', icon: 'success' });
          setTimeout(() => {
            wx.navigateBack();
          }, 800);
        } else {
          wx.showToast({ title: res.data?.message || '发布失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络异常，请稍后重试', icon: 'none' });
      },
      complete: () => {
        this.setData({ submitting: false });
      }
    });
  }
}); 